<?php
include_once "../common/http.class.php";
include_once "../common/stringutils.class.php";
include_once "../common/image.class.php";
class auto{
	private $db;
	private $log;
	private $config;
	private $url_index = "http://car.autohome.com.cn/zhaoche/pinpai/";
	private $url_car = "http://www.autohome.com.cn/?/options.html";
	private $url_py = "http://car.autohome.com.cn/price/serchtips.html";
	public static $autolog_dir = "/logo/";
	function __construct($config,$db,$log){
		$this->config = $config;
		$this->db = $db;
		$this->log = $log;
	}
	public function brand_all(){
		$list = array();
		$pylist = $this->db->query_first_all('select distinct py from auto_brand where py is not null order by py');
		if(count($pylist)>0){
			foreach($pylist as $py){
				$sql = "select id,name,icon_link,link,utime from auto_brand where py='$py'";
				$brand_list = $this->db->query_assoc_all($sql);
				if(count($brand_list)>0){
					$list[$py]=$brand_list;
					foreach ($brand_list as $idx=>$brand){
						$list[$py][$idx][series_count]=$this->series_count($brand[id]);
					}
				}
			}
		}
		return $list;
	}
	public function brand_query($brand_id){
		return $this->db->query_assoc("select * from auto_brand where id='$brand_id'");
	}
	public function series_count($brand_id){
		return $this->db->query_first("select count(*) from auto_series where brand_id='$brand_id'");
	}
	public function series_query($brand_id){
		return $this->db->query_assoc_all("select * from auto_series where brand_id='$brand_id'");
	}
	public function cars_query($series_id){
		return $this->db->query_assoc_all("select * from auto_car where series_id='$series_id'");
	}
	public function car_price($car_id){
		return $this->db->query_first("select car_value from auto_config where car_id='$car_id' and item_name='厂商指导价(元)'");
	}
	public function series_crawl(){
		$this->log->debug("start crawling series...");
		$this->log->debug("crawling  ".$this->url_index);
		$tmp = Http::request($this->url_index);
		$html = mb_convert_encoding($tmp, 'utf-8','gb2312');
		$list = stringutils::betweens($html, 'grade_js_top30','grade_js_top30');
		unset($html);
		$image = new image();
		foreach ($list as $idx => $brandhtml){
			if($idx==0 || $idx == count($list)-1)continue;
			$tmp = stringutils::between($brandhtml,'grade_js_top33">','</div>');
			$brand_link = stringutils::between($tmp,'<a href="','"');
			$brand_name = stringutils::between($tmp,'">','</a>');
			$brand_id = stringutils::between($brand_link,'brand-','.html');

			//if($this->db->query_first("select id from auto_brand where id='$brand_id'")){//不重复更新
				//continue;
			//}

			/* 将LOGO保存到本地 */
			$tmp = stringutils::between($brandhtml,'grade_js_top32','</div>');
			$icon_url = stringutils::between($tmp,'<img src="','"');
			$dest_dir = dirname(__FILE__).auto::$autolog_dir;
			$dest_name = basename($icon_url);
			if(!file_exists($dest_dir.$dest_name)){
				$dest_path = http::request_file($icon_url, $dest_dir,$dest_name);
			}
			if(!file_exists($dest_dir."16_".$dest_name)){
				$image->resize($dest_dir.$dest_name, null, 16, $dest_dir."16_".$dest_name,'h');
			}
			$brand_icon = auto::$autolog_dir.$dest_name;
			$this->db->update("delete from auto_brand where id='$brand_id'");
			$sql = "insert into auto_brand(id,name,link,icon_link,utime) values('$brand_id','$brand_name','$brand_link','$brand_icon',".time().")";
			$this->db->update($sql);
			$serieshtmllist = stringutils::betweens($brandhtml,'grade_js_top10">','</div>');
			if($serieshtmllist && count($serieshtmllist)>0){
				foreach($serieshtmllist as $serieshtml){
					$series_link = stringutils::between($serieshtml,'<a href="','"');
					$series_name = stringutils::between($serieshtml,'">','</a>');
					$series_id = stringutils::between($series_link,'cn/','/');

					//if($this->db->query_first("select id from auto_series where id='$series_id'")){//不重复更新
						//continue;
					//}
					$this->db->update("delete from auto_series where id='$series_id'");
					$sql = "insert into auto_series(id,brand_id,name,link,utime) values('$series_id','$brand_id','$series_name','$series_link',".time().")";
					$this->db->update($sql);
				}
			}
		}
		$this->log->debug("crawling series done.");
		return true;
	}

	public function key_crawl(){
		$idlist = $this->db->query_first_all('select id from auto_series limit 20');
		if(count($idlist)>0){
			foreach($idlist as $id){
				$url = str_replace('?', $id, $this->url_car);
				$html = Http::request($url);
				if($html){
					$tmp = stringutils::between($html,'var keyLink = {','}','gb2312');
					if($tmp){
						$key_json = mb_convert_encoding($tmp, 'utf-8','gb2312');
						$key_json = '{'.$key_json.'}';
						$key_arr = json_decode($key_json);
						if(count($key_arr)>0){
							/* 删除旧数据 */
							$this->db->update('delete from auto_key where 1');
							/* 保存数据库 */
							foreach($key_arr as $key_name=>$key_link){
								$sql = "insert into auto_key(name,link,ts) values('$key_name','$key_link',".time().")";
								$this->db->update($sql);
							}
							return true;
						}
					}
				}
			}
		}
		return true;
	}

	public function cars_crawl(){
		$this->log->debug("start crawling cars...");
		$idlist = $this->db->query_first_all('select id from auto_series');
		if(count($idlist)>0){
			foreach($idlist as $series_id){
				$url = str_replace('?', $series_id, $this->url_car);
				$this->log->debug("crawling $url");
				$tmp = Http::request($url);
				if($tmp){
					$html = mb_convert_encoding($tmp, 'utf-8','gb2312');
					// 保存配置1
					$config_json = stringutils::between($html,' var config = {','}]}]}}');
					if($config_json){
						$config_json = '{'.$config_json.'}]}]}}';
						$tmp = json_decode($config_json);
						$config_arr = $this->object_array($tmp);
						$items_arr = $config_arr[body][items];
						if(count($items_arr)>0){
							foreach($items_arr as $item){
								$item_type_id = $item[ItemType];
								$item_type_name = $item[Item];
								$item_name = $item[Name];
								if(count($item[ModelExcessIds])>0){
									foreach($item[ModelExcessIds] as $car){
										$car_id = $car[Id];
										$car_value = $car[Value];
										//if($this->db->query_first("select 1 from auto_config where series_id='$series_id' and item_type_id='$item_type_id' and item_name='$item_name' and car_id='$car_id'")){
											//continue;
										//}
										$this->db->update("delete from auto_config where series_id='$series_id' and item_type_id='$item_type_id' and item_name='$item_name' and car_id='$car_id'");
										$sql = "insert into auto_config(series_id,item_type_id,item_type_name,item_name,car_id,car_value,ts) values('$series_id','$item_type_id','$item_type_name','$item_name','$car_id','$car_value',".time().")";
										$this->db->update($sql);
									}
								}
							}
						}
					}

					// 保存配置2
					$config_json = stringutils::between($html,'var option = {','}]}]}}');
					if($config_json){
						$config_json = '{'.$config_json.'}]}]}}';
						$tmp = json_decode($config_json);
						$config_arr = $this->object_array($tmp);
						$items_arr = $config_arr[body][items];
						if(count($items_arr)>0){
							foreach($items_arr as $item){
								$item_type_id = $item[ItemType];
								$item_type_name = $item[Item];
								$item_name = $item[Name];
								if(count($item[ModelExcessIds])>0){
									foreach($item[ModelExcessIds] as $car){
										$car_id = $car[Id];
										$car_value = $car[Value];
										//if($this->db->query_first("select 1 from auto_option where series_id='$series_id' and item_type_id='$item_type_id' and item_name='$item_name' and car_id='$car_id'")){
											//continue;
										//}
										$this->db->update("delete from auto_option where series_id='$series_id' and item_type_id='$item_type_id' and item_name='$item_name' and car_id='$car_id'");
										$sql = "insert into auto_option(series_id,item_type_id,item_type_name,item_name,car_id,car_value,ts) values('$series_id','$item_type_id','$item_type_name','$item_name','$car_id','$car_value',".time().")";
										$this->db->update($sql);
									}
								}
							}
						}
					}
					
					$color_json = stringutils::between($html,'var color = {','}]}]}}');
					if($color_json){
						$tmp = json_decode($color_json);
						$color_arr = $this->object_array($tmp);
						if(count($color_arr)>0){
							$items_arr = $color_arr[body][items];
							if(count($items_arr)>0){
								foreach($items_arr as $item){
									$car_id = $item[SpecId];
									$colorlist = $item[ColorList];
									if(count($colorlist)>0){
										foreach($colorlist as $color){
											$this->db->update("delete from auto_color where car_id='$car_id' and code='$color[Value]'");
											$sql = "insert into auto_color(car_id,code,name,link,ts) values('$car_id','$color[Value]','$color[Name]','$color[PicLink]',".time().")";
											$this->db->update($sql);
										}
									}
								}
							}
						}
					}
				}
				/* 保存车辆信息 */
				$this->db->update("delete from auto_car where series_id='$series_id'");
				$this->db->update("insert into auto_car(id,series_id,name) select car_id,series_id,car_value from auto_config where series_id='$series_id' and item_name='车型名称'");
			}
		}
		$this->log->debug("crawling cars done.");
		return true;
	}
	public function pinyin_update(){
		$tmp = Http::request($this->url_py);
		$tmp2 = mb_convert_encoding($tmp, 'utf-8','gb2312');
		$html = stringutils::between($tmp2,'allBrand','<div class="clear"></div></div>','gb2312');
		$dllist = stringutils::betweens($html,'<dl>','</dl>');
		if(count($dllist)>0){
			foreach($dllist as $dl){
				$py = stringutils::between($dl,'<dt class="letter">','</dt>');
				$dd = stringutils::between($dl,'<dd>','</dd>');
				$brandlist = stringutils::betweens($dd,'>','</a>');
				foreach ($brandlist as $brand){
					$c = mb_substr($brand, 0,1,'utf-8');
					$this->db->update("update auto_brand set py='$py' where name like '$c%'");
				}
			}
		}
		return true;
	}
	private function object_array($array){
		if(is_object($array)){
			$array = (array)$array;
		}
		if(is_array($array)){
			foreach($array as $key=>$value){
				$array[$key] = $this->object_array($value);
			}
		}
		return $array;
	}
} ?>
